<template>
  <Dialog
    v-model="dialogVisible"
    width="800px"
    :title="typeIndex === 'add' ? t('staff.add') : t('staff.edit')"
    :before-close="() => closeDialog(formRef)"
    :close-on-click-modal="true"
    maxHeight="680px"
  >
    <el-form :model="form" ref="formRef" label-width="110px">
      <!-- 修改点1：增加状态区分和错误提示 -->
      <el-form-item :label="t('manualBook.file_url')" prop="file_list">
        <UploadFilesBase
          ref="uploadRef"
          class="w-full"
          :directory="2"
          :limit="99"
          :fileListMap="form.file_list"
          @upload-success-res="handleUploadCallback"
        />
      </el-form-item>

      <el-form-item :label="t('video.pm_names')" class="w-95%" prop="pids" required>
        <el-input
          v-model="productDisplayText"
          disabled
          :placeholder="'请选择' + t('video.pm_names')"
        >
          <template #append>
            <el-button size="small" type="primary" @click="handleOpenMining">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submit(formRef)">{{ t('common.save') }}</el-button>
    </template>
    <DialogProduct
      ref="DialogProductRef"
      @expose-multiple-data="getExposeProductData"
      :multiple="true"
      :pagination="false"
    />
  </Dialog>
</template>

<script setup lang="ts">
import { createImageViewer } from '@/components/ImageViewer'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
import DialogProduct from '@/components/Dialog/src/ProductMerge/Index.vue'
import { editInfoApi, createDataApi } from '@/api/manualBook'

const emit = defineEmits(['refresh'])
const { t } = useI18n()

// 新增：文件大小限制配置
const maxFileSize = 1024 * 1024 * 1024 // 1GB（单位：字节）
const maxFileSizeMB = Math.round(maxFileSize / (1024 * 1024)) // 转换为MB

const dialogVisible = ref<boolean>(false)
const typeIndex = ref<string>()
const currencyList = ref<Array<Record<string, any>>>([])
const showList = ref<Array<Record<string, any>>>([])
const productDisplayText = ref('')
// 修改点2：加强错误状态管理
const uploadError = ref<string>('')
const getDropDownBoxInfo = async () => {}
const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  file_list: [],
  // title: '',
  pids: '',
  type: 2
})

const DialogProductRef = ref<any>(null)

const handleOpenMining = () => {
  nextTick(() => {
    DialogProductRef!.value!.dialogVisible = true
    const selectedProducts = form.value.pids
      ? form.value.pids.split(',').map((id: string) => ({ id: parseInt(id.trim()) }))
      : []
    console.log('selectedProducts', selectedProducts)
    DialogProductRef!.value!.initialize(selectedProducts)
  })
}

const getExposeProductData = (val: any) => {
  console.log('333', val)
  form.value.pids = val.map((item: any) => item.id).join(',')
  productDisplayText.value = val.map((item: any) => item.productname).join(',')
}

const picList = ref<any[]>([])
const uploadRef = ref<any>(null)
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 修改点3：严格检查文件状态
        // if (!fileObj.value || fileObj.value.status !== 'success') {
        //   ElMessage.error(t('manualBook.uploadFailedTip'))
        //   return
        // }
        let result = await uploadRef.value?.uploadImg()
        console.log('result', result)
        if (result) {
          ElMessage.warning('上传中,请稍等')
          return
        }
        console.log('picList.value', picList.value)
        let fileIds = form.value.file_list.map((item: any) => item.id).join(',')
        const params = {
          file_id: fileIds,
          id: form.value.id,
          pids: form.value.pids,
          type: 2
        }
        const resp =
          typeIndex.value === 'add' ? await createDataApi(params) : await editInfoApi(params)

        if (resp && resp.code === 0) {
          ElMessage.success(
            typeIndex.value === 'add'
              ? t('manualBook.createSuccess')
              : t('manualBook.updateSuccess')
          )
          closeDialog(formEl)
          emit('refresh')
        }
      } catch (error) {
        console.error('提交失败', error)
      }
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    file_list: [],
    // title: '',
    pids: ''
  }
  // 修改点4：重置所有上传状态
  uploadError.value = ''
  picList.value = []
  fileObj.value = null
  productDisplayText.value = ''
  formEl.resetFields()
  dialogVisible.value = false
}

const getBackShow = (type: string, row?: Record<string, any>) => {
  typeIndex.value = type
  picList.value = []
  uploadError.value = ''
  getDropDownBoxInfo()
  fileObj.value = null
  if (type === 'edit') {
    form.value.id = row!.id
    form.value.file_list = row!.file_list.map((item: any) => ({
      id: item.file_id,
      name: item.file_name,
      url: item.file_url
    }))
    form.value.pids = row!.pids
    if (row!.product_list) {
      productDisplayText.value = row!.product_list
    }
    console.log('form.value', form.value)
  }
}

defineExpose({
  dialogVisible,
  getBackShow
})
//上传成功以后回调
const handleUploadCallback = (val: any) => {
  console.log('val3333344', val)
  form.value.file_list.push(...val)
  console.log('val33333', val, form.value.file_list)
}
const fileObj = ref<any>(null)
// const handleUploadCallback = (val: any) => {
//   // 修改点6：上传成功时明确标记状态
//   const fileData = { ...val, status: 'success' }
//   picList.value = [fileData] // 只保留成功文件
//   fileObj.value = fileData
//   uploadError.value = ''
// }

// 修改点7：完整错误处理逻辑
const handleUploadError = (error: any, file: File) => {
  console.error('文件上传失败:', error, file)
  // 新增：文件大小错误判断
  uploadError.value = t('manualBook.uploadFailedTip')
  // 立即清除失败文件
  picList.value = []
  fileObj.value = null
}

const handleRemoveFile = (val: any) => {
  picList.value = []
  fileObj.value = null
  uploadError.value = ''
}

const handlePictureCardPreview = (url: any) => {
  try {
    if (!url) return
    if (url.toLowerCase().endsWith('.pdf')) {
      window.open(url, '_blank')
      return
    }

    if (/\.(jpg|jpeg|png|gif|bmp)$/i.test(url))
      return createImageViewer({
        urlList: [url]
      })
    window.open(url)
  } catch (error) {
    console.error('预览失败:', error)
  }
}
</script>

<style lang="less" scoped>
.m-r-4 {
  margin-right: 16px;
}

.el-upload__tip--error {
  margin-top: 7px;
  font-size: 12px;
  color: #f56c6c;
}

/* 新增：文件大小提示样式 */
.el-upload__tip {
  margin-top: 7px;
  font-size: 12px;
  color: #909399;
}
</style>
